const { 
  BrowserWindow, 
  app, 
  session, 
  dialog, 
  ipcMain,
  globalShortcut,
  Menu,
  Tray,
  desktopCapturer,
  screen,
  Notification
} = electron = require('electron')

const windowStateKeeper = require('electron-window-state')
const path = require('path')

const copyImage = require('./copyImg')

let win, tray
let mainMenu = Menu.buildFromTemplate( require('./mainMenu') )

let contextMenu = Menu.buildFromTemplate([
  { label: 'Item 1' },
  { role: 'editMenu' }
])

let trayMenu = Menu.buildFromTemplate([
  { label: 'Item 1' },
  { role: 'quit' }
])

function createTray() {
  tray = new Tray('trayTemplate.png')
  tray.setToolTip('Tray details')

  tray.on('click', e => {
    if (e.shiftKey) {
      app.quit()
    } else {
      win.isVisible() ? win.hide() : win.show()
    }
  })
  // tray.setContextMenu(trayMenu)
}

const openWindow = () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize
  // console.log(width, height)

  Menu.setApplicationMenu(mainMenu)
  createTray()

  let mainWindowState = windowStateKeeper({
    defaultWidth: width,
    defaultHeight: height
  })

  win = new BrowserWindow({
    x: mainWindowState.x,
    y: mainWindowState.y,
    width: mainWindowState.width,
    height: mainWindowState.height,
    width,
    height,
    minHeight: 400,
    minWidth: 400,
    show: false,
    resizable: true,
    frame: true,
    icon: './app@2x.png',
    webPreferences: {
      // // 是否在renderer端开启node
      // nodeIntegration: false,
      // // 是否启用运行环境隔离
      // contextIsolation: true,

      // 是否允许在render进程里调用main的模块(已废弃)
      // enableRemoteModule: true,

      // 是否允许使用window.open
      nativeWindowOpen: true,
      // 在启动应用时在rederer里预加载js
      preload: path.join(__dirname, './preload-js/index.js')
    }
  })

  mainWindowState.manage(win)

  // 在打开的窗口里加载内部入口文件
  win.loadFile('./index.html')
  // win.loadURL('https://www.qq.com')

  // 打开devtools窗口
  win.webContents.openDevTools()

  win.once('ready-to-show', () => {
    win.show()
  })

  setTimeout(() => {
    // win.maximize()
  }, 3000)

  const wc = win.webContents
  wc.on('dom-ready', () => {
    // console.log('dom-ready')
  })

  wc.on('did-finish-load', () => {
    // console.log('did-finish-load')

    // dialog.showOpenDialog({
    //   buttonLabel: 'select',
    //   defaultPath: app.getPath('music'),
    //   properties: ['openFile', 'openDirectory']
    // }).then(({filePaths}) => {
    //   console.log(filePaths)
    // })

  }) 

  wc.on('context-menu', (e, param) => {
    // console.log(param.selectionText)
    contextMenu.popup()
    
    // 调用拷贝图片的方法
    const { mediaType, srcURL } = param
    if (mediaType === 'image') {
      copyImage(srcURL, wc)
    }
  })

  wc.on('context-menu', (e, params) => {
    // wc.executeJavaScript(`alert('${params.selectionText}')`)
  })


  // const customSess = session.fromPartition('persist:part1')

  // const win2 = new BrowserWindow({
  //   width: 800,
  //   height: 600,
  //   // parent: win,
  //   // modal: true,
  //   resizable: false,
  //   webPreferences: {
  //     nodeIntegration: true,
  //     contextIsolation: false,
  //     nativeWindowOpen: true,
  //     // session: customSess
  //     partition: 'persist:part1'
  //   }
  // })

  // win2.loadFile('./index.html')
  // win2.webContents.openDevTools()

  // const wc2 = win2.webContents

  // const sess = wc.session
  // const sess2 = wc2.session
  // const defalutSess = session.defaultSession

  // console.log(Object.is(sess, sess2, defalutSess))

  // 删除所有的Cookies
  // defalutSess.cookies.get({})
  // .then((cookies) => {
  //   cookies.forEach((cookie) => {
  //     defalutSess.cookies.remove(cookie.domain, cookie.name)
  //   })
  // }).catch((error) => {
  //   console.log(error)
  // })

  // defalutSess.cookies.get({})
  // .then((cookies) => {
  //   console.log(cookies)
  //   // cookies.length = 0
  // }).catch((error) => {
  //   console.log(error)
  // })

  // const cookie = { url: 'http://www.github.com', name: 'dummy_name', value: 'dummy' }
  // sess2.cookies.set(cookie)

  // sess2.cookies.get({ url: 'http://www.github.com', name: 'dummy_name' })
  // .then((cookies) => {
  //   console.log(cookies)
  // }).catch((error) => {
  //   console.log(error)
  // })


  ipcMain.on('btn-click', (msg) => {
    const answers = ['Yes', 'No', 'Maybe']
    dialog.showMessageBox({
      title: 'Message Box',
      message: 'Please select an option',
      detail: 'Message details.',
      buttons: answers
    }).then(({response}) => {
      console.log(answers[response])
    })
  })

  if (process.platform === 'darwin') {
    app.dock.setIcon(path.join(__dirname, 'app.png'));
  }

  // 弹出操作系统级别消息窗口
  const notification = new Notification({
    title: '一条消息',
    body: '马上放假了。'
  })
  setTimeout(() => {
    notification.show()
  }, 5000)
}

// 应用就绪后打开窗口
app.whenReady().then(() => {
  openWindow()

  // console.log(app.getPath('desktop'))
  // console.log(app.getPath('music'))
  // console.log(app.getPath('temp'))
  // console.log(app.getPath('userData'))

  setTimeout(() => {
    const wins = BrowserWindow.getAllWindows()
    // wins[0].hide()
  }, 3000)

  if(app.isReady()) {
    // console.log('readed.')
  }

  // globalShortcut.register('G', () => {
  //   console.log('G')
  // })

  // globalShortcut.register('CommandOrControl+Y', () => {
  //   console.log('User pressed G with a combination key')
  //   globalShortcut.unregister('CommandOrControl+Y')
  // })
})

app.on('before-quit', () => {
  // console.log('before-quit')
})

app.on('browser-window-blur', () => {
  // console.log('browser-window-blur')
  // app.quit()
})

app.on('browser-window-focus', () => {
  // console.log('browser-window-focus')
})
